<template>
  <div class="app-container">
    <el-card shadow="always" style="margin-top: 15px">
      <div class="header">
        <div class="title">
          <span></span>
          <p>文件列表</p>
        </div>

        <div>
          <el-button
            type="primary"
            size="small"
            plain
            @click="last"
            v-if="browse_history.length != 0"
            >上一级
          </el-button>
          <el-dropdown
            trigger="click"
            style="margin: 0 10px"
            @command="addFile"
          >
            <el-button type="success" size="small" plain>
              新增<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1">新建空白文本</el-dropdown-item>
              <el-dropdown-item command="2">新建文件夹</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <uploadFile
            text="上传文件"
            action="/api/api/uploadServeFile"
            :data="uploadParmse"
            @success="fileUpload_success"
            @beforeFileUpload="beforeFileUpload"
            style="margin-right: 10px"
            @error="upload_error"
          ></uploadFile>

          <el-button
            size="small"
            @click="delFile(false)"
            type="danger"
            v-if="selectTable.length != 0"
          >
            <i class="el-icon-delete-solid">批量删除</i>
          </el-button>

          <el-button
            size="small"
            @click="paste"
            type="success"
            v-if="shearPlate || shearPlates.length != 0"
          >
            <i class="el-icon-copy-document">粘贴</i>
          </el-button>

          <el-button
            size="small"
            @click="shear(false)"
            type="success"
            v-if="selectTable.length != 0"
          >
            <i class="el-icon-scissors">剪切</i>
          </el-button>

          <el-button
            size="small"
            @click="shear(false, true)"
            type="success"
            v-if="selectTable.length != 0"
          >
            <i class="el-icon-copy-document">复制</i>
          </el-button>

          <el-button size="small" @click="getInit">
            <i class="el-icon-refresh-right">刷新</i>
          </el-button>
        </div>
      </div>

      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>根目录</el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{ path: '/' }"
          v-for="(item, index) in browse_history"
          :key="index"
          >{{ item.name }}</el-breadcrumb-item
        >
      </el-breadcrumb>

      <TableView
        :data-list="dataList"
        :loading="loading"
        @pagination="pagination"
        :showPagination="false"
        @onSelectionChange="selectionChange"
        height="73vh"
        ref="table"
        style="margin-top: 10px"
      >
        <div slot="column">
          <el-table-column
            label="文件名"
            align="center"
            prop="name"
            width="200"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="smaill"
                @click="clickFileName(scope.row)"
                v-if="!scope.row.flag && scope.row.type == 'directory'"
                >{{ scope.row.name }}</el-button
              >

              <span v-if="scope.row.type != 'directory' && !scope.row.flag">{{
                scope.row.name
              }}</span>

              <el-input
                v-if="scope.row.flag"
                placeholder="请输入文件名称"
                v-model="scope.row.name"
                @change="saveServeFile(scope.row)"
                ref="input"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            label="文件大小"
            align="center"
            prop="size"
            show-overflow-tooltip
          />

          <el-table-column
            label="修改日期"
            align="center"
            prop="formattedDate"
            show-overflow-tooltip
          />

          <el-table-column
            label="权限"
            align="center"
            prop="permissions"
            show-overflow-tooltip
          />

          <el-table-column
            label="硬链接数"
            align="center"
            prop="links"
            show-overflow-tooltip
          />

          <el-table-column
            label="文件所有者"
            align="center"
            prop="owner"
            show-overflow-tooltip
          />

          <el-table-column
            label="所属组"
            align="center"
            prop="group"
            show-overflow-tooltip
          />

          <el-table-column
            label="文件路径"
            align="center"
            prop="path"
            show-overflow-tooltip
          />

          <el-table-column
            label="操作"
            align="center"
            width="250"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="delFile(scope.row)"
                >删除</el-button
              >
              <el-button
                type="text"
                @click="editFileName(scope.row)"
                v-if="!scope.row.flag"
                >重命名</el-button
              >

              <el-button
                type="text"
                @click="decompression(scope.row)"
                v-if="['zip', '7z', 'rar'].includes(scope.row.type)"
                >解压</el-button
              >

              <el-button
                type="text"
                @click="shear(scope.row)"
                v-if="!scope.row.flag"
                >剪切</el-button
              >

              <el-button
                type="text"
                @click="shear(scope.row, true)"
                v-if="!scope.row.flag"
                >复制</el-button
              >

              <el-button
                type="text"
                @click="scope.row.flag = false"
                v-if="scope.row.flag && scope.row.path"
                >取消</el-button
              >
            </template>
          </el-table-column>
        </div>
      </TableView>
    </el-card>
  </div>
</template>

<script>
import {
  addServeFile,
  decompressionServeFile,
  delServeFile,
  editServeFile,
  getServeFiles,
  moveServeFile,
} from "@/api/databaseManagement";
import uploadFile from "@/components/uploadFile";

import TableView from "@/components/TableView/index.vue";
export default {
  components: {
    TableView,
    uploadFile,
  },
  data() {
    return {
      dataList: [],
      loading: false,
      browse_history: [],
      uploadParmse: {},

      // /shear 剪切板内容
      shearPlate: "",
      shearPlates: [],

      // 记录是否为复制文件
      isCopy: false,

      // 选择表格元素
      selectTable: [],
    };
  },

  mounted() {
    this.getInit();
  },

  methods: {
    async getInit() {
      this.loading = true;
      let filePath = "/";
      if (this.browse_history.length) {
        filePath = this.browse_history[this.browse_history.length - 1].path;
      }
      const res = await getServeFiles({ filePath });
      if (res.code == 20000) {
        this.dataList = res.data || [];

        this.$refs.table.doLayout();
      } else {
        this.$message.error(res.msg);
      }
      this.loading = false;
    },

    // 点击文件名
    clickFileName(item) {
      if (item.type != "directory") {
        return;
      }
      this.browse_history.push(item);
      this.getInit();
    },

    // 点击上一级/
    last() {
      if (this.browse_history.length) {
        this.browse_history.pop();
        this.getInit();
      }
    },

    // 新增文件
    async addFile(e) {
      if (
        this.dataList.length != 0 &&
        this.dataList[this.dataList.length - 1].flag
      ) {
        let dataListLength = this.dataList.length - 1;
        if (this.dataList[dataListLength].flag) {
          this.$message.warning("请先保存文件");
          return;
        }
      }

      this.dataList.push({
        name: "",
        fileType: e,
        flag: true,
      });

      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },

    // 输入文件名框失去焦点
    async saveServeFile(item) {
      if (!item.name) {
        this.$message.warning("文件名不能为空");
        return;
      }
      item.flag = false;

      // 新增文件
      if (!item.path) {
        try {
          this.loading = true;
          let length = this.browse_history.length - 1;
          let parmse = {
            filePath:
              this.browse_history[length].path +
              "/" +
              this.dataList[this.dataList.length - 1].name, // 新增文件地址
            fileType: this.dataList[this.dataList.length - 1].fileType, // 新增文件类型
          };
          await addServeFile(parmse);
          this.getInit();
          this.dataList.pop(); //删除最后一个元素
        } catch (error) {
          this.$message.error(error);
        }
      } else {
        // 重命名
        let oldPath = item.path;
        // 将地址的最后一个/xx 替换为当前输入的值
        let newPath =
          this.browse_history[this.browse_history.length - 1].path +
          "/" +
          item.name;
        try {
          await editServeFile({ oldPath, newPath });
        } catch (error) {
          this.$message.error(error);
        }
      }
    },

    // 删除
    delFile(item) {
      console.log(item, "item");

      let detailFileList = [];
      let detailFile = "";
      if (item) {
        if (item.flag && !item.path) {
          this.dataList.pop();
          return;
        }
        detailFile = item.path;
      } else {
        console.log(this.selectTable, "this.selectTable");

        if (this.selectTable.length != 0) {
          // 判断要删除的文件 是不是 存在 item.flag && !item.path 判断条件
          this.selectTable.forEach((row) => {
            console.log(row);

            if (row.flag && !row.path) {
              this.dataList.pop();
            } else {
              detailFileList.push(row.path);
            }
          });
        }
      }
      console.log(this.selectTable, "this.selectTable");
      console.log(detailFileList, "detailFileList");
      console.log(detailFile, "detailFile");

      this.$confirm("确定要删除这个服务器文件吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        this.loading = true;
        try {
          let result = await delServeFile({
            path: detailFile || detailFileList,
          });
          if (result.code == 20000) {
            this.$message.success("删除成功");
            this.getInit();
          } else {
            this.$message.error(result.msg);
          }
        } catch (error) {
          this.$message.error(error);
        }
      });
    },

    // 重命名
    editFileName(item) {
      item.flag = true; //设置文件名称可输入
    },

    // 上传文件之前
    beforeFileUpload(file) {
      this.loading = true;
      this.uploadParmse.serverPath =
        this.browse_history[this.browse_history.length - 1].path || "/"; //获取文件名 传给服务器
    },

    // 文件上传失败
    upload_error() {
      this.loading = false;
    },

    // 上传文件--成功
    fileUpload_success(e) {
      let { res } = e;
      if (res.code == 20000) {
        this.$message.success("文件上传成功");
        this.getInit();
      } else {
        this.$message.error(res.msg);
      }
    },

    // 解压压缩文件
    async decompression(item) {
      this.$confirm("确定解压当前压缩包吗？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      }).then(async () => {
        try {
          this.loading = true;
          // 当前文件夹位置
          let destination =
            this.browse_history[this.browse_history.length - 1].path;

          let result = await decompressionServeFile({
            // 要解压的文件
            filePath: item.path,
            destination: destination,
          });
          if (result.code == 20000) {
            this.$message.success("解压成功,文件数量：" + result.data.length);
            this.getInit();
          } else {
            this.$message.error(result.msg);
            this.loading = false;
          }
        } catch (error) {
          this.$message.error(error);
          this.loading = false;
        }
      });
    },

    // 剪切文件
    shear(item, isCopy = false) {
      if (item) {
        this.shearPlate = item.path;
      } else {
        if (this.selectTable.length != 0) {
          this.shearPlate = this.selectTable.map((item) => item.path);
        }
      }

      this.isCopy = isCopy;

      this.$message.success(
        `${
          this.isCopy ? "复制" : "剪切"
        }成功,请点击右上角粘贴按钮,粘贴文件到指定目录`
      );
    },

    // 粘贴文件
    paste() {
      this.$confirm("确定粘贴当前文件吗？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      }).then(async () => {
        try {
          this.loading = true;
          let destination =
            this.browse_history.length == 0
              ? "/"
              : this.browse_history[this.browse_history.length - 1].path;
          let result = await moveServeFile({
            fileNames: this.shearPlate || this.shearPlates,
            destination: destination,
            isCopy: this.isCopy,
          });

          if (result.code == 20000) {
            this.$message.success("粘贴成功");
            this.shearPlate = "";
            this.shearPlates = [];
            this.getInit();
          } else {
            this.$message.error(result.msg);
            this.loading = false;
          }
        } catch (error) {
          this.$message.error(error);
          this.loading = false;
        }
      });
    },

    rest() {
      this.seachForm = {};
      this.getInit();
    },

    pagination(e) {
      this.seachForm = e;
      this.getInit();
    },

    // 选择表格
    selectionChange(e) {
      this.selectTable = e;
      console.log(this.selectTable, "selectTable");
    },
  },
};
</script>

<style></style>
